package monitor

import (
	"html/template"
	"net/http"
	"strconv"
	"time"
)

import (
	"buyChance"
	"r_log"
	"util"
)

/*
处理特定周期状态的页面
*/

type SpecificState struct {
	ExecTime     time.Time
	Time         util.DateAndTime
	Date         util.DateAndTime
	Isvalid      bool
	DetailStates []DetailState
}
type DetailState struct {
	StockID        string
	StkID          util.StkID
	AvgTransaction int64
	Assigned       int64
	Type           util.ModeType
	Level          util.Level
}

func (d *SpecificState) init(p util.Period) {
	bcb := &buyChance.BCBase
	d.ExecTime = time.Now()
	d.Time = bcb.BuyChances[p].Time
	d.Date = bcb.BuyChances[p].Date
	now := time.Now()
	date := util.Today()
	time := util.DateAndTime(now.Hour()*10000 + now.Minute()*100 + now.Second())
	ts := util.GeneratorTimestamp(date, time)
	d.Isvalid = bcb.BuyChances[p].IsValid(ts, false)
	bcb.BcLock[p].Lock()
	bcb.DdsSocket.StkMapLock.RLock()
	d.DetailStates = nil
	for stkid, bc := range bcb.BuyChances[p].BcMap {
		if stockid, ok := bcb.DdsSocket.StkMapSH[uint32(stkid)]; ok {
			d.DetailStates = append(d.DetailStates, DetailState{StockID: stockid[0:10], StkID: stkid, AvgTransaction: bc.AvgTransaction / 100, Assigned: bc.AssignedTransaction / 100, Type: bc.Type, Level: bc.Level})
			continue
		}
		if stockid, ok := bcb.DdsSocket.StkMapSZ[uint32(stkid)]; ok {
			d.DetailStates = append(d.DetailStates, DetailState{StockID: stockid[0:10], StkID: stkid, AvgTransaction: bc.AvgTransaction / 100, Assigned: bc.AssignedTransaction / 100, Type: bc.Type, Level: bc.Level})
			continue
		}
	}
	bcb.DdsSocket.StkMapLock.RUnlock()
	bcb.BcLock[p].Unlock()
}

// state周期 模板传回
func (s *SpecificState) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		r_log.Logger.Warn("SpecificState Get Request is not resolving: %v", err)
	}
	p, err := strconv.Atoi(r.Form["period"][0])
	if err != nil {
		r_log.Logger.Warn("period atoi is faild: %v", err)
	}
	s.init(util.Period(p)) // todo 初始化数据  发送get请求时获取周期
	t := template.Must(template.ParseFiles(monitorunit.MonitorConf.DetailStateAddr))
	err = t.Execute(w, s)
	if err != nil {
		r_log.Logger.Warn("StateInfo template execute is faild: %v", err)
	}
}
